/*
** hashtables.c for zappy in /home/chris/Rendu/B4/UNIX/zappy/pateyproject/server
** 
** Made by christophe lecointe
** Login   <lecoin_c@epitech.net>
** 
** Started on  Fri May 25 13:07:57 2012 christophe lecointe
** Last update Thu May 31 12:03:52 2012 christophe lecointe
*/

#include "server.h"
#include <string.h>
#include <stdlib.h>

static pid_t		hashFunc(pid_t id)
{
  pid_t	res;

  if ((res = id >> HASHDIV) >= MAX_TABLE_SIZE)
    return (MAX_TABLE_SIZE - 1);
  return (res);
}

void		initTable(t_pTable *playerList)
{
  memset((*playerList), 0, MAX_TABLE_SIZE * sizeof(t_player *));
}

int		addPlayer(t_pTable *playerList, t_player *player)
{
  pid_t	tmp;

  /* Fonction de test à enlever pour le rendu */
  if (player->id < 0)
    exit(-1000);
  /* END */
  tmp = hashFunc(player->id);
  if (tmp == (hashFunc(player->id - 1) + 1))
    {
      add_in_list((*playerList)[getPrevList((*playerList), tmp - 1)], player);
      (*playerList)[tmp] = player;
    }
  else if ((*playerList)[tmp] == NULL)
    {
      add_in_list((*playerList)[getPrevList((*playerList), tmp)], player);
      (*playerList)[tmp] = player;
    }
  else
    add_in_list((*playerList)[tmp], player);
  return (1);
}

t_player	*getPlayer(t_pTable *playerList, pid_t id)
{
   return (get_player_from_list((*playerList)[hashFunc(id)], id));
}

void		removePlayer(t_pTable *playerList, t_player *player)
{
  pid_t	tmp;

  /* Fonction de test à enlever pour le rendu */
  if (player->id < 0)
    exit(-1000);
  /* END */
  tmp = hashFunc(player->id);
  if ((*playerList)[tmp] == player)
    {
      if (tmp != 0)
	(*playerList)[tmp] = remove_from_list((*playerList)[getPrevList((*playerList), tmp - 1)], player);
      else
	(*playerList)[0] = remove_from_list((*playerList)[tmp], player);
    }
  else
    remove_from_list((*playerList)[tmp], player);
}
